/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import database.DataEngine;
import database.UserInfo;
import java.util.List;
import log.LogDef;
import log.LogWriter;
import processer.RoBot;
import utils.Debug;

/**
 *
 * @author daz
 */
public class BotManager implements Runnable {

//    private static final int THREAD_DELAY = 60000;
    private static final int THREAD_DELAY = 5000;
    private boolean isRunning;
    private int maxRobot;
    private DataEngine dataEngine;
    private String host;
    private String hostPort;
    private LogWriter objWriter = null;
    private String csPath = "";
    private String _csModuleName = "Robot_Fun";
    private byte _nLogLevel = LogDef.LOG_LEVEL.LOG_INFO;
    private int numberAdd = 10;
    private Counter counter;

    public BotManager(int numberRobot, String host, String hostPort) {
        this.maxRobot = numberRobot;
        this.host = host;
        this.hostPort = hostPort;
        counter = new Counter();
        dataEngine = DataEngine.getInstance();
        if (Debug.isTest) {
            maxRobot = 1;
        }
    }

    public synchronized void logUserStatus(String logMsg, byte nLevel) {
        if (objWriter != null) {
            objWriter.writeLog(logMsg, nLevel);
        } else {
//            System.out.println("logger null");
        }
    }

    public synchronized void logError(String logMsg, Throwable throwable) {
        if (objWriter != null) {
            objWriter.writeError(logMsg, throwable);
        } else {
        }
    }

    private void initLogger() {
        //Init logger
        objWriter = new LogWriter(_csModuleName, _nLogLevel);

        objWriter.setFileLogInfo(true, csPath, _csModuleName,
                LogDef.FILE.CHANGE_ON_SZIE, //Change file when maximum size reached
                LogDef.FILE.MAX_FILE_SIZE / 10, //1M
                LogDef.FILE.MAX_FILE_BACKUP_INDEX,// 1000 file per day
                false //flush immediately
                );
        objWriter.setSysLogInfo(true, "localhost", 513);
        objWriter.setConsoleInfo(true);

        objWriter.open();
    }

    public void start() {
        isRunning = true;
        Thread mainThread = new Thread(this);
        mainThread.start();
    }

    @Override
    public void run() {
        while (isRunning) {
            try {
                Thread.sleep(THREAD_DELAY);
            } catch (InterruptedException ex) {
            }
//            printMemory();
            try {//                
                if (counter.getValue() < maxRobot) {
                    List<UserInfo> userInfoList = dataEngine.getRobot(numberAdd);
                    Debug.d("counter :" + userInfoList.size());
                    if (!userInfoList.isEmpty()) {
                        for (int i = 0; i < userInfoList.size(); i++) {
                            UserInfo user = userInfoList.get(i);
                            Debug.d("user name :" + user.getUserName());
//                            dataEngine.activateAcc(user.getUserName());
                            dataEngine.setUserOnline(1, user.getUserName());
                            RoBot roBot = new RoBot(counter.getValue(), user.getUserName(), user.getUserPassword(), host, hostPort);
//                            logUserStatus("robot id :" + counter.getValue(), LogDef.LOG_LEVEL.LOG_INFO);
                            roBot.setManager(this);
                            roBot.start();
                            counter.increment();
                            System.out.println("thread.count=" + Thread.getAllStackTraces().size());
                            Runtime.getRuntime().gc();
                        }
                    }
                } else {
//                    isRunning = false;
                }
            } catch (Exception ex) {
                dataEngine = DataEngine.getInstance();
            }
        }
    }

    public synchronized void kickUser() {
        counter.decrement();
    }

    private void printMemory() {
//        System.out.println("Max memory    :" + (Runtime.getRuntime().maxMemory() >> 20));
        System.out.println("--------------------------------------------------------------");
        System.out.println("thread.count=" + Thread.getAllStackTraces().size());
        System.out.println("Free memory   :" + (Runtime.getRuntime().freeMemory() >> 20));
//        System.out.println("Total memmory :" + (Runtime.getRuntime().totalMemory() >> 20));
        System.out.println("Use memmory :" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20));
        Runtime.getRuntime().gc();

    }

    void setLogFilePath(String logFilePath) {
        this.csPath = logFilePath;
        initLogger();
    }
}
